<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

class ZpriorityObject extends ObjectModel
{
	public 		$id;


	/** @var string Name */
	public 		$priority;

	/** @var boolean Status for display */
	public 		$active = 1;


	/** @var string Description */
	public 		$description;

	/** @var string Object creation date */
	public 		$date_add;
	/** @var string Backgroud color for status */
	public 		$backgroud_color='#ffffff';
	
	/** @var string text color for status */
	public 		$text_color='#000000';
	
	/** @var int number position for status */
	public 		$position;

	protected $tables = array ('zhelpdesk_ticket_priority', 'zhelpdesk_ticket_priority_lang');

	protected 	$fieldsRequired = array('active');
 	protected 	$fieldsSize = array('active' => 1);
 	protected 	$fieldsValidate = array('active' => 'isBool');
	protected 	$fieldsRequiredLang = array('priority');
 	protected 	$fieldsSizeLang = array('priority' => 64);
 	protected 	$fieldsValidateLang = array('priority' => 'isCatalogName','description' => 'isCleanHtml');

	protected 	$table = 'zhelpdesk_ticket_priority';
	protected 	$identifier = 'id_zhelpdesk_ticket_priority';

	public function __construct($id = NULL, $id_lang = NULL) {
		parent::__construct($id, $id_lang);
	}

	public function getFields()
	{
		parent::validateFields();
		if (isset($this->id))
			$fields['id_zhelpdesk_ticket_priority'] = (int)($this->id);
		$fields['active'] = (int)($this->active);
		$fields['date_add'] = pSQL($this->date_add);
		$fields['backgroud_color'] = pSQL($this->backgroud_color);
		$fields['text_color'] = pSQL($this->text_color);
		$fields['position'] = pSQL($this->position);
		return $fields;
	}

	/**
	  * Check then return multilingual fields for database interaction
	  *
	  * @return array Multilingual fields
	  */
	public function getTranslationsFieldsChild()
	{
		parent::validateFieldsLang();
		return parent::getTranslationsFields(array('priority', 'description'));
	}

	
	/**
	 * @see ObjectModel::toggleStatus()
	 */
	public function toggleStatus()
	{
		$result = parent::toggleStatus();
		return $result;
	}
	/**
	 * Same parent but add position
	 * @param unknown_type $autodate
	 * @param unknown_type $nullValues
	 */
	public	function add($autodate = true, $nullValues = false)
	{
		$this->position = self::getLastPosition();
		$ret = parent::add($autodate);
		return $ret;
	}
	/**
	 * update category positions in parent
	 *
	 * @param mixed $nullValues
	 * @return void
	 */
	public function update($nullValues = false)
	{
		// Update group selection
		$this->cleanPositions();
		// If the parent category was changed, we don't want to have 2 categories with the same position
		if ($this->getDuplicatePosition())
			$this->position = self::getLastPosition();
		$ret = parent::update($nullValues);
		return $ret;
	}
	public function delete()
	{
		parent::delete();
		self::cleanPositions();
		return true;
	}
	
	/**
	 * when change status
	 * @param unknown_type $way
	 * @param unknown_type $position
	 */
	
    public function updatePosition($way, $position)
	{
		if (!$res = Db::getInstance()->ExecuteS('
			SELECT *
			FROM `' . _DB_PREFIX_ . $this->table . '` cp
			ORDER BY cp.`position` ASC'
		))
			return false;
			
	
		foreach ($res AS $category)
			if ((int)($category['id_zhelpdesk_ticket_priority']) == (int)($this->id))
				$movedCategory = $category;
		
		if (!isset($movedCategory) || !isset($position))
			return false;
		
		// < and > statements rather than BETWEEN operator
		// since BETWEEN is treated differently according to databases
		$result = (Db::getInstance()->Execute('
			UPDATE `' . _DB_PREFIX_ . $this->table . '`
			SET `position` = `position` '.($way ? '- 1' : '+ 1').'
			WHERE `position`
			'.($way
				? '> '.(int)($movedCategory['position']).' AND `position` <= '.(int)($position)
				: '< '.(int)($movedCategory['position']).' AND `position` >= '.(int)($position))
			)
		AND Db::getInstance()->Execute('
			UPDATE `' . _DB_PREFIX_ . $this->table . '`
			SET `position` = '.(int)($position).'
			WHERE `id_zhelpdesk_ticket_priority`='.(int)($movedCategory['id_zhelpdesk_ticket_priority'])));
		return $result;
	}
 	/**
	 * cleanPositions keep order of category in $id_zhelpdesk_ticket_priority_parent,
	 * but remove duplicate position. Should not be used if positions
	 * are clean at the beginning !
	 *
	 * @param mixed $id_zhelpdesk_ticket_priority_parent
	 * @return boolean true if succeed
	 */
	public static function cleanPositions()
	{
		$return = true;

		$result = Db::getInstance()->ExecuteS('
		SELECT *
		FROM `' . _DB_PREFIX_ .'zhelpdesk_ticket_priority`
		ORDER BY `position`');
		$sizeof = sizeof($result);
		
		for ($i = 0; $i < $sizeof; $i++){
				$sql = '
				UPDATE `' . _DB_PREFIX_ .'zhelpdesk_ticket_priority`
				SET `position` = '.(int)($i).'
				WHERE `id_zhelpdesk_ticket_priority` = '.(int)($result[$i]['id_zhelpdesk_ticket_priority']);
				$return &= Db::getInstance()->Execute($sql);
			}
		return $return;
	}
	/**
	 * Search for another category with the same parent and the same position
	 *
	 * @return array first category found
	 */
	public function getDuplicatePosition()
	{
		return Db::getInstance()->getRow('
		SELECT c.`id_zhelpdesk_ticket_priority` as id
		FROM `' . _DB_PREFIX_ . $this->table . '` c
		WHERE `position` = '.(int)($this->position).'
		AND c.`id_zhelpdesk_ticket_priority` != '.(int)($this->id));
	}
	
	/** this function return the number of category + 1 having $id_zhelpdesk_ticket_priority_parent as parent.
	 * 
	 * @todo rename that function to make it understandable (getNewLastPosition for example)
	 * @param int $id_zhelpdesk_ticket_priority_parent the parent category
	 * @return int
	 */
	public static function getLastPosition()
	{
		$rs = Db::getInstance()->getRow('SELECT  MAX(position)+1 as nb FROM `' . _DB_PREFIX_ .'zhelpdesk_ticket_priority`');
		return ($rs['nb']);
	}
	
	/**
	 * display color for list content width item backround-color and text-color
	 * @param unknown_type $list
	 * 					list item display bf
	 */
	public static function getStyleListContent ($list){
		$nb = self::getLastPosition();
		$rs= '
		<style type="text/css"> ';
		foreach ($list as $item) {
			for ($i=0;$i<$nb;$i++) 
				$rs.='
					tr#tr_1_'.$item['id_zhelpdesk_ticket_priority'].'_'.$i.' td:nth-child(3)
					{
						background-color:'.$item['backgroud_color'].';
						color:'.$item['text_color'].';
						text-align:center;
						font-weight: bold;
						border-radius: 6px;
					}';
		}
		$rs.='	
			</style>';
		return $rs;
	}
	/**
	 * get all priority to array
	 * @return array ('name'=>'name_priority', 'value'=>'id_zhelpdesk_ticket_priority')
	 */
	public static function getAllPriority($id_lang=0,$active=true)
	{
		global $cookie;
		
		return Db::getInstance()->ExecuteS(' 
			SELECT * 
			FROM '._DB_PREFIX_.'zhelpdesk_ticket_priority ztp 
			LEFT JOIN '._DB_PREFIX_.'zhelpdesk_ticket_priority_lang ztpl ON (ztp.id_zhelpdesk_ticket_priority=ztpl.id_zhelpdesk_ticket_priority AND id_lang='.$cookie->id_lang.')
			'.($active==true?'WHERE active=1':'').'
			ORDER BY `position`'
		);
	}
        
        /**
	 * get all priority to array
	 * @return array ('name'=>'name_priority', 'value'=>'id_zhelpdesk_ticket_priority')
	 */
	public static function getSelectPriority()
	{
		global $cookie;
		
		return Db::getInstance()->ExecuteS(' 
			SELECT ztp.id_zhelpdesk_ticket_priority as value, ztpl.`priority` as name 
			FROM '._DB_PREFIX_.'zhelpdesk_ticket_priority ztp 
			LEFT JOIN '._DB_PREFIX_.'zhelpdesk_ticket_priority_lang ztpl ON (ztp.id_zhelpdesk_ticket_priority=ztpl.id_zhelpdesk_ticket_priority AND id_lang='.$cookie->id_lang.')'
		);
	}
	/**
	 * Get Priority min is default
	 */
	public static function getDefaultPriority () {
		return (Db::getInstance()->getValue('SELECT id_zhelpdesk_ticket_priority FROM '. _DB_PREFIX_.'zhelpdesk_ticket_priority ORDER BY position'));
	}
}

